package com.android.vmg;

import android.content.*;
import android.os.*;
import android.view.*;
import android.graphics.*;
import android.util.*;

import java.util.*;

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

	private GameThread thread;

	public GameView(Context context) {
		super(context);
		init(context);
	}
	
	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}
	
	public GameView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}
	
	private void init(Context context) {
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
                
        thread = new GameThread(holder, this);
        thread.setDaemon(true);

        setFocusable(true);
        setVisibility(VISIBLE);
	}
	
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
    	if(hasWindowFocus)
    		thread.unpause();
    	else
    		thread.pause();
    }
	
//	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        thread.setSurfaceSize(width, height);
	}

//	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		thread.setSurfaceSize(arg0.getSurfaceFrame().width(), arg0.getSurfaceFrame().height());
		thread.setRunning(true);
		thread.start();
	}

//	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		finish();
	}
	
	public void finish() {
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            	Log.w("", e.getMessage());
            }
        }

	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN)
			thread.doTouch((int)(event.getX()), (int)(event.getY()));
		return super.onTouchEvent(event);
	}
	
	public GameThread getThread() {
		return thread;
	}
}
